package com.wsd.smartcarwasher.service;

import com.github.pagehelper.PageHelper;
import com.wsd.smartcarwasher.dao.OrderDao;
import com.wsd.smartcarwasher.dao.StatisticDao;
import com.wsd.smartcarwasher.dao.WashServiceDao;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.util.DateUtil;
import com.wsd.smartcarwasher.util.ReturnUtil;
import com.wsd.smartcarwasher.util.TimeUtil;
import com.wsd.smartcarwasher.util.TimeUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StatisticService {
    private static final Logger logger = LoggerFactory.getLogger(StatisticService.class);
    @Resource
    private StatisticDao statisticDao;
    @Resource
    @Lazy
    private MachineService machineService;
    @Resource
    private WashServiceDao washServiceDao;
    @Resource
    private OrderService orderServicer;
    @Resource
    @Lazy
    private OrderDao orderDao;
    @Resource
    @Lazy
    private OfflineCountRecordService offlineCountRecordService;
    @Lazy
    @Resource
    private SysDicService sysDicService;
    @Lazy
    @Resource
    private PartnerService partnerService;
    public StatisticService() {
    }

    public Map<String, Object> queryTurnoverTrend(String type, List<Integer> machineIds,Integer partnerId) {
        String dateFormat = this.getDateFormat(type);
        String time = null;
        if(type.equals("day"))
        {
            time=DateUtil.format(new Date(),"yyyy-MM-dd");

        }else if(type.equals("week"))
        {
            time=DateUtil.format(new Date(),"yyyy-ww");
        }
        else if(type.equals("month"))
        {
            time=DateUtil.format(new Date(),"yyyy-MM");
        }
        List<OrderStatistics> statistics = this.statisticDao.queryTurnoverTrendOfMachines(dateFormat, machineIds,partnerId,time);
        String unit = "";
        if ("week".equalsIgnoreCase(type)) {
            unit = "周";
        }

        return this.changeStatisticToMap(statistics, unit);
    }

    private Map<String, Object> changeStatisticToMap(List<OrderStatistics> statistics, String unit) {
        List<String> times = (List)statistics.stream().map((o) -> {
            return o.getTime() + unit;
        }).collect(Collectors.toList());
        List<BigDecimal> turnovers = (List)statistics.stream().map(OrderStatistics::getTurnover).collect(Collectors.toList());
        List<Integer> orderSizes = (List)statistics.stream().map(OrderStatistics::getOrderSize).collect(Collectors.toList());
        Map<String, Object> resultMap = new HashMap();
        resultMap.put("xLabels", times);
        resultMap.put("turnover_data", turnovers);
        resultMap.put("orders_data", orderSizes);
        return resultMap;
    }

    private Map<String, Object> changeStatisticToMap_new(List<OrderStatistics> statistics, String unit,Integer partnerId,Integer machineId) {
        List<String> times = (List)statistics.stream().map((o) -> {
            return o.getTime() + unit;
        }).collect(Collectors.toList());
        List<BigDecimal> turnovers = (List)statistics.stream().map(OrderStatistics::getTurnover).collect(Collectors.toList());
        List<Integer> orderSizes = (List)statistics.stream().map(OrderStatistics::getOrderSize).collect(Collectors.toList());
        List<Integer> offlineCount=new ArrayList<>();
        for (String time:times
             ) {

            offlineCount.add(this.offlineCountRecordService.getOfflineCountRecord(time,partnerId,machineId));
        }


        Map<String, Object> resultMap = new HashMap();
        resultMap.put("xLabels", times);
        resultMap.put("turnover_data", turnovers);
        resultMap.put("orders_data", orderSizes);
        resultMap.put("offlineCount", offlineCount);
        return resultMap;
    }

    private String getDateFormat(String type) {
        byte var4 = -1;
        switch(type.hashCode()) {
            case 99228:
                if (type.equals("day")) {
                    var4 = 2;
                }
                break;
            case 3645428:
                if (type.equals("week")) {
                    var4 = 0;
                }
                break;
            case 104080000:
                if (type.equals("month")) {
                    var4 = 1;
                }
        }

        String dateFormat;
        switch(var4) {
            case 0:
                dateFormat = "%Y-%u";
                break;
            case 1:
                dateFormat = "%Y-%m";
                break;
            case 2:
            default:
                dateFormat = "%Y-%m-%d";
        }

        return dateFormat;
    }

    public Pagination<OrderInfo> queryOrderInfoWithPagination(List<Integer> machineIds, int pageNum, int pageSize,Integer id) {
        List<OrderInfo> orders = this.queryOrderInfoByMachineIds(machineIds,id);
        return new Pagination(pageNum, pageSize, orders);
    }
    public  List<OrderInfo> queryUserWashingOrder(String userId) {
        String startTime=DateUtil.getCurrentDate();
        List<OrderInfo> orders = this.statisticDao.queryWashOrder(userId,startTime);
        if (orders == null) {
            orders = Collections.emptyList();
        }

        return orders;
    }


    public List<OrderInfo> queryUserOrder(String userId,Integer machineId) {

        List<OrderInfo> orders = this.orderDao.queryUserOrder(userId,machineId);
        if (orders == null) {
            orders = Collections.emptyList();
        }else{
            for (OrderInfo o:orders
            ) {
                o.setPayPrice(o.getPayPrice().setScale(2, RoundingMode.HALF_UP));
                o.setOrderPrice(o.getOrderPrice().setScale(2,RoundingMode.HALF_UP));
            }
        }
        return orders;
    }

//    /**
//     * 小程序用户查看消费记录
//     * @param userId
//     * @param machineId
//     * @return
//     */
//    public List<OrderInfo> queryUserOrderByApplets(String userId,Integer machineId) {
//
//        List<OrderInfo> orders = this.orderDao.queryUserOrderByApplets(userId,machineId);
//        if (orders == null) {
//            orders = Collections.emptyList();
//        }else{
//            for (OrderInfo o:orders
//            ) {
//                o.setPayPrice(o.getPayPrice().setScale(2, RoundingMode.HALF_UP));
//                o.setOrderPrice(o.getOrderPrice().setScale(2,RoundingMode.HALF_UP));
//            }
//        }
//        return orders;
//    }




    public Map<String, List<OrderInfo>> queryUserUnfinishedOrders(String userId,Integer machineId) {
        List<OrderInfo> orders = this.queryUserOrder(userId,machineId);
        List<OrderInfo> unPayedOrders = new ArrayList();
        List<OrderInfo> unConsumedOrders = new ArrayList();
        Iterator var5 = orders.iterator();

        while(var5.hasNext()) {
            OrderInfo order = (OrderInfo)var5.next();
            if (order.getPayStatus() != 2) {
                unPayedOrders.add(order);
            } else if (order.getConsumed() == 0 && order.getEndTime() == null) {
                unConsumedOrders.add(order);
            }
        }
        Map<String, List<OrderInfo>> orderMap = new HashMap();
        orderMap.put("unPayedOrders", unPayedOrders);
        orderMap.put("unConsumedOrders", unConsumedOrders);
        return orderMap;
    }

    public List<OrderPieStatistic> getStatisticInfo(List<Integer> machineIds, String type,Integer id) {
        List<OrderInfo> orders = this.queryOrderInfoByMachineIds(machineIds,id);
        return this.statisticOrderByType(orders, type);
    }

    private List<OrderPieStatistic> statisticOrderByType(List<OrderInfo> orders, String type) {
        if (orders == null) {
            orders = new ArrayList();
        }

        List<OrderPieStatistic> result = new ArrayList();
        Map groupMap;
        if ("timeQuantum".equalsIgnoreCase(type)) {
            groupMap = this.groupByTimeQuantum((List)orders);
            result.add(new OrderPieStatistic("0时-6时", this.getStatisticInfoFromMap(groupMap, "0")));
            result.add(new OrderPieStatistic("6时-12时", this.getStatisticInfoFromMap(groupMap, "1")));
            result.add(new OrderPieStatistic("12时-18时", this.getStatisticInfoFromMap(groupMap, "2")));
            result.add(new OrderPieStatistic("18时-24时", this.getStatisticInfoFromMap(groupMap, "3")));
        } else if ("serviceType".equalsIgnoreCase(type)) {
            groupMap = this.groupByServiceType((List)orders);
            List<WashService> services = this.washServiceDao.queryAllWashServices();
            Iterator var6 = services.iterator();

            while(var6.hasNext()) {
                WashService washService = (WashService)var6.next();
                result.add(new OrderPieStatistic(washService.getName(), this.getStatisticInfoFromMap(groupMap, String.valueOf(washService.getId()))));
            }
        } else if ("payWay".equalsIgnoreCase(type)) {
            groupMap = this.groupByPayWay((List)orders);
            result.add(new OrderPieStatistic("会员卡", this.getStatisticInfoFromMap(groupMap, "2")));
            result.add(new OrderPieStatistic("微信支付", this.getStatisticInfoFromMap(groupMap, "1")));
        }

        return result;
    }


    public Map<String,Object> getPoportion(String sTime,String eTime) {
        Map<String,Object> map=new HashMap<>();
        DecimalFormat decimalFormat=new DecimalFormat("0.00");
        //用户数构成
        
        
        double allCustomer= Double.valueOf(this.statisticDao.getallCustomer(sTime,eTime).get("allCustomer").toString());
        double newCustomer= Double.valueOf(this.statisticDao.getNewCustomer(sTime,eTime).get("newCustomer").toString());
        double oldCustomer=allCustomer-newCustomer;
        if(oldCustomer>=0)
        {
            map.clear();
            map.put("newCustomer",decimalFormat.format(newCustomer/allCustomer));
            map.put("oldCustomer",decimalFormat.format(oldCustomer/allCustomer));
        }

        //所有用户交易金额构成
        Map<String,Object> allTradeMap= this.statisticDao.getAllCustomerPrice(sTime,eTime);
        //新用户交易金构成
        Map<String,Object> newTradeMap= this.statisticDao.getNewCustomerPrice(sTime,eTime);


        //所选日期金额数
        double allCustomertraderAmount=Double.valueOf(allTradeMap.get("allCustomerPrice").toString());
        double newCustomertraderAmount=Double.valueOf(newTradeMap.get("newCustomerPrice").toString());
        map.put("newCustomerPricePro",decimalFormat.format(newCustomertraderAmount/allCustomertraderAmount));

        //所选日期的交易笔数
        double allCustomerTraderNumber=Double.valueOf(allTradeMap.get("allTraderNumber").toString());
        double newCustomerTraderNumber=Double.valueOf(newTradeMap.get("newTraderNumber").toString());
        map.put("newCustomerNumber",decimalFormat.format(newCustomerTraderNumber/allCustomerTraderNumber));
        return ReturnUtil.Success("success",map);
    }


    private Map<String, List<OrderInfo>> groupByTimeQuantum(List<OrderInfo> orders) {
        return (Map)orders.parallelStream().collect(Collectors.groupingBy((order) -> {
            return order.getCreateTime() == null ? null : String.valueOf(order.getCreateTime().getHours() / 6);
        }));
    }

    private Map<String, List<OrderInfo>> groupByServiceType(List<OrderInfo> orders) {
        return (Map)orders.parallelStream().collect(Collectors.groupingBy((order) -> {
            return String.valueOf(order.getServiceId());
        }));
    }

    private Map<String, List<OrderInfo>> groupByPayWay(List<OrderInfo> orders) {
        return (Map)orders.parallelStream().collect(Collectors.groupingBy((order) -> {
            return String.valueOf(order.getPayWayCode());
        }));
    }

    private Integer getStatisticInfoFromMap(Map<String, List<OrderInfo>> group, String key) {
        List<OrderInfo> value = (List)group.get(key);
        return CollectionUtils.isEmpty(value) ? 0 : value.size();
    }

    private List<OrderInfo> queryOrderInfoByMachineIds(List<Integer> machineIds,Integer id) {

       List<OrderInfo> orders = this.orderDao.queryOrderInfoByMachineIds(machineIds,id);
        return orders == null ? Collections.emptyList() : orders;
    }
    private List<OrderInfo> queryOrderInfoByMachineIdsByRu(List<Integer> machineIds,Integer id) {
        List<OrderInfo> orders = this.statisticDao.queryOrderInfoByMachineIdsByRu(machineIds,id);
        return orders == null ? Collections.emptyList() : orders;
    }



    public Map<String, Object> getStatistics(Partner partner) {

        List<Machine> machines = this.machineService.getMachinesByPartnerId(partner.getId());
        if (CollectionUtils.isEmpty(machines)) {
            return null;
        } else {
            List<Integer> machineIds = (List)machines.parallelStream().map(Machine::getId).distinct().collect(Collectors.toList());

            List<OrderInfo> orders = this.queryOrderInfoByMachineIds(machineIds,partner.getId());
            return this.getTurnoverStatistics(orders, true);
        }
    }

    private Map<String, Object> getTurnoverStatistics(List<OrderInfo> orders, boolean isRunner) {

        if (orders == null) {
            orders = new ArrayList();
        }

        Date date = DateUtil.getSysDate();
        Date dateBack7 = DateUtil.getDateBack(6);
        Date dateBack30 = DateUtil.getDateBack(29);
        BigDecimal turnover_1 = new BigDecimal(0.0D);
        BigDecimal turnover_7 = new BigDecimal(0.0D);
        BigDecimal turnover_30 = new BigDecimal(0.0D);
        int orders_1 = 0;
        BigDecimal profit_1 = new BigDecimal(0.0D);
        Iterator var11 = ((List)orders).iterator();

        while(var11.hasNext()) {
            OrderInfo order = (OrderInfo)var11.next();
            Date createTime = order.getCreateTime();//DateUtil.convertToGMT(order.getCreateTime());
            if (createTime != null) {
                if (createTime.getTime() > date.getTime()) {
                    ++orders_1;
                    turnover_1 = turnover_1.add(order.getPayPrice());
                    profit_1 = profit_1.add(order.getPayPrice());
                }

                if (createTime.getTime() > dateBack7.getTime()) {
                    turnover_7 = turnover_7.add(order.getPayPrice());
                }

                if (createTime.getTime() > dateBack30.getTime()) {
                    turnover_30 = turnover_30.add(order.getPayPrice());
                }
            }
        }

        Map<String, Object> result = new HashMap();
        result.put("turnover_1", turnover_1.setScale(2, 4).toString());
        result.put("turnover_7", turnover_7.setScale(2, 4).toString());
        result.put("turnover_30", turnover_30.setScale(2, 4).toString());
        if (isRunner) {
            result.put("profit_1", profit_1.setScale(2, 4).toString());
        }

        result.put("orders_1", orders_1);
        return result;
    }

    public Map<String, Object> getPcTurnoverStatistics(String machineId,Integer partnerId) {
        List<OrderInfo> orders = this.orderDao.queryOrderInfoByMachineId(machineId,partnerId);
        System.out.println("D");
        return this.getTurnoverStatistics(orders, false);
    }

    public static void main(String[] args) {

//        System.out.println(new StatisticService().getDateFormat("month"));
        System.out.println(TimeUtil.format(new Date(),"yyyy-MM-dd"));
        System.out.println(TimeUtil.format(TimeUtils.addDay(new Date(),-30),"yyyy-MM-dd"));
        System.out.println(DateUtil.format(new Date(),new StatisticService().getDateFormat("week")));
    }



    public Map<String, Object> queryPcTurnoverTrend(String machineId, String type,Integer partnerId) {
        String dateFormat = this.getDateFormat(type);
        String createTime=null;
        Integer format=null;
        List<OrderStatistics> statistics =new ArrayList<>();
        if(dateFormat.equals("%Y-%m"))
        {
            createTime="%Y";
            format=Integer.valueOf(DateUtil.getCurrentYear());
            statistics = this.statisticDao.queryTurnoverTrend(dateFormat, machineId,partnerId,createTime,format);
//            Collections.reverse(statistics);
        }else if(dateFormat.equals("%Y-%m-%d"))
        {
            createTime="%m";
            format=Integer.valueOf(DateUtil.getCurrentMonth());
            String startTime=TimeUtil.format(TimeUtils.addDay(new Date(),1),"yyyy-MM-dd");
            String endTime=TimeUtil.format(TimeUtils.addDay(new Date(),-30),"yyyy-MM-dd");
            statistics = this.statisticDao.queryTurnoverTrend30Day(dateFormat, machineId,partnerId,createTime,startTime,endTime,format);

        }else if(dateFormat.equals("%Y-%u"))
        {
            createTime="%m";
            format=Integer.valueOf(DateUtil.getCurrentMonth());
            statistics = this.statisticDao.queryTurnoverTrend(dateFormat, machineId,partnerId,createTime,format);
        }
        String unit = "";
        if ("week".equalsIgnoreCase(type)) {
            unit = "周";
        }
        return this.changeStatisticToMap(statistics, unit);
    }

    public List<OrderPieStatistic> getPcPieChart(String machineId, String type, Integer partnerId) {

        List<OrderInfo> orders = this.statisticDao.queryOrderInfoByMachineId(machineId,partnerId);
        return this.statisticOrderByType(orders, type);
    }

    public OrderInfo queryOrderInfoByOrderSn(String orderSn) {
        return this.statisticDao.queryOrderInfoByOrderSn(orderSn);
    }

    /**
     * 各种数量的统计 设备 门店 订单
     * @return
     */
    public ModelMap getAllNumberStatistics() {
        Map<String,Object> map = this.statisticDao.getAllNumberStatistics();
        return ReturnUtil.Success("获取成功",map);
    }

    public ModelMap getStoreNumberStatistics(int partnerId) {
        Map<String,Object> map = this.statisticDao.getStoreNumberStatistics(partnerId);
        return ReturnUtil.Success("获取成功",map);
    }

    public ModelMap getAllOrderTop10() {
        List<Map<String,Object>> map = this.statisticDao.getAllOrderTop10();
        return ReturnUtil.Success("获取成功",map);
    }

    public ModelMap getAllDataView(String sTime,String eTime,int partnerId) {


            //交易金额、交易笔数、顾客数
            List<String> timeList = Arrays.asList(sTime.split(","));
            Map<String,Object> map=new HashMap<>();
            Map<String,Object> map1=new HashMap<>();

                map.put(sTime,this.statisticDao.getAllNumberView(sTime,eTime,partnerId));
                //顾客构成
                //查询日期或者所选时间段的新用户userId、用户userId
                //回流
                Integer backflowDays=Integer.parseInt(this.sysDicService.getByCode(1013).get(0).getValue());
                //回归
                Integer flybackDays=Integer.parseInt(this.sysDicService.getByCode(1014).get(0).getValue());

                map1.put(sTime,this.statisticDao.getCustomerUserid(sTime,eTime,partnerId,backflowDays,flybackDays));

                ModelMap modelMap=new ModelMap();
                modelMap.addAttribute("trade",map);
                modelMap.addAttribute("customer",map1);
                return ReturnUtil.Success("查询成功",modelMap);
    }

    /**
     * 所选日期每间隔两小时的时段数据
     * @param sTime
     * @return
     */
    public ModelMap getTimeDataView(String sTime,int partnerId) {

            //从所选时间日期的零点设置，每两个小时的数据
            List<String> timeList=new ArrayList<>();
            Date time=DateUtil.convertStringToDate(sTime);
            for(int i=1;i<=12;i++)
            {
                timeList.add(DateUtil.format(time,DateUtil.DATE_TIME_PATTERN));
                time=TimeUtils.addHour(time,2);

            }
            Map<String,Object> map=new HashMap<>();

            for (String d:timeList
            ) {
                Map<String,Object> number=this.statisticDao.getAllNumberView(d,DateUtil.format(TimeUtils.addHour(DateUtil.stringToDate(d,DateUtil.DATE_TIME_PATTERN),2),DateUtil.DATE_TIME_PATTERN),partnerId);
                map.put(d+"",number);
            }
            return ReturnUtil.Success("查询成功",map);

    }
 /**
     * 所选日期每天(星期制)的时段数据
     * @param sTime
     * @return
     */
    public Map<String, Object> getWeekDataView(String sTime, int partnerId) {

            //从所选时间日期的零点设置，每两个小时的数据
            List<String> timeList=new ArrayList<>();
            Date time=DateUtil.convertStringToDate(sTime);
            for(int i=1;i<=7;i++)
            {
                timeList.add(DateUtil.format(time,DateUtil.DATE_TIME_PATTERN));
                time=TimeUtils.addDay(time,1);
            }
            Map<String,Object> map=new HashMap<>();

            for (String d:timeList
            ) {
                Map<String,Object> number=this.statisticDao.getAllNumberView(d,DateUtil.format(TimeUtils.addDay(DateUtil.stringToDate(d,DateUtil.DATE_TIME_PATTERN),2),DateUtil.DATE_TIME_PATTERN),partnerId);
                map.put(TimeUtil.getWeekOfDate(DateUtil.stringToDate(d,DateUtil.DATE_TIME_PATTERN)),number);
            }

            return map;

    }

    /**
     * 近30天内新老顾客的数量概览
     * @param sTime
     * @return
     */
    public ModelMap getMonthDataView(Integer partnerId,Date sTime,int day) {
        //从所选时间日期的零点开始，选择日期往前30天
        List<String> timeList=new ArrayList<>();
        Date time=TimeUtil.addDayTrue(sTime,-day);
//回流
        Integer backflowDays=Integer.parseInt(this.sysDicService.getByCode(1013).get(0).getValue());
        //回归
        Integer flybackDays=Integer.parseInt(this.sysDicService.getByCode(1014).get(0).getValue());

        Map<String,Object> map=this.statisticDao.getCustomerUserid(DateUtil.format(time,DateUtil.DATE_TIME_PATTERN),DateUtil.format(sTime,DateUtil.DATE_TIME_PATTERN),partnerId,backflowDays,flybackDays);
        return ReturnUtil.Success("查询成功",map);
    }
    /**
     * 所选日期或时间段的顾客数量变化//回流客backflowDays   回归客flybackDays
     * @param sTime
     * @return
     */
    public ModelMap getDayDataView(Integer partnerId,String sTime,String eTime) {
//回流
        Integer backflowDays=Integer.parseInt(this.sysDicService.getByCode(1013).get(0).getValue());
        //回归
        Integer flybackDays=Integer.parseInt(this.sysDicService.getByCode(1014).get(0).getValue());

        //从所选时间日期的零点开始
        List<String> timeList = new ArrayList<>();
        int count=0;
        while(!eTime.equals(sTime))
        {
            timeList.add(sTime);
            sTime=DateUtil.format(TimeUtil.addDayTrue(DateUtil.stringToDate(sTime,DateUtil.DATE_TIME_PATTERN),1),DateUtil.DATE_TIME_PATTERN);
            count++;
            if(count==30)
            {break;}
        }
        Map<String,Object> map=new HashMap<>();
        for (String time:timeList
             ) {
                map.put(time,this.statisticDao.getCustomerUserid(time,DateUtil.format(TimeUtil.addDayTrue(DateUtil.stringToDate(time,DateUtil.DATE_TIME_PATTERN),1),DateUtil.DATE_TIME_PATTERN),partnerId,backflowDays,flybackDays));
    }
        return ReturnUtil.Success("查询成功",map);
    }




    /**
     * pc端主页统计订单趋势
     * @param machineId
     * @param partnerId
     * @param sTime
     * @param eTime
     * @return
     */
    public ModelMap getAllStatistics(Integer machineId, Integer partnerId, String sTime, String eTime) {

        List<OrderStatistics> statistics=new ArrayList<>();
        if(StringUtils.isNotBlank(eTime) &&StringUtils.isNotBlank(sTime)){

            Date ddeTime = DateUtil.stringToDate(eTime,"yyyy-MM-dd");
            Date ddesTime = DateUtil.stringToDate(sTime,"yyyy-MM-dd");
            ddeTime = DateUtil.getDateLater(ddeTime, +1);
            if(ddeTime.after(ddesTime)){

                statistics=   this.statisticDao.queryTurnoverTrendByIndex(machineId,partnerId,ddesTime,ddeTime);
            }else{
                return ReturnUtil.Error("结束时间不能大于起始时间!!");
            }
        }else{
            Date deTime =new Date();
            Date desTime = DateUtil.getDateLater(deTime, -7);
            statistics=   this.statisticDao.queryTurnoverTrendByIndex(machineId,partnerId,desTime,deTime);
        }


        Map<String, Object> map =  this.changeStatisticToMap_new(statistics, "",partnerId,machineId);
        return ReturnUtil.Success("获取成功",map);
    }


    public Pagination queryOrderInfoWithPaginationRu(List<Integer> machineIds, int pageNum, int pageSize, Integer id) {
        PageHelper.startPage(pageNum,pageSize);
        List<OrderInfo> orders = this.orderDao.queryOrderInfoByMachineIdsByRu(machineIds,id);
        for (OrderInfo o:orders
             ) {
            o.setMachineName(this.machineService.queryMachineById(o.getMachineId()).getName());
        }
        return new Pagination(pageNum, pageSize, orders);
    }



//    /**
//     * 配置
//     * 获取新顾客、回流客、回归客
//     * @param dayBackFlow
//     * @param dayFlyback
//     * @param sTime
//     * @param eTime
//     * @return
//     */
//    public Map<String,Object> customerType(Integer dayBackFlow,Integer dayFlyback,String sTime,String eTime)
//    {
//        Map<String,Object> cumtomers=new HashMap<>();
//
////      查询规定时间段内的之前登录且下单时间早于现在时间的userId
//        List<OrderInfo> orderCustomers=this.statisticDao.queryOrderCustomer(sTime);
//        List<String> orderCustomersList=new ArrayList<>();
//        if(orderCustomers.isEmpty())
//        {
//            return null;
//        }
//        for (OrderInfo s:orderCustomers
//             ) {
//            orderCustomersList.add(s.getUserId());
//        }
//        //转字符串
//        String Customers = StringUtils.join(orderCustomersList.toArray(),",");
//       //查询规定时间段的回流客时间末端值
//        Date stime=DateUtil.stringToDate(sTime,DateUtil.DATE_TIME_PATTERN);
//        String BackFlowTime=DateUtil.format(TimeUtils.addDay(stime,dayBackFlow),DateUtil.DATE_TIME_PATTERN);
//        //查询规定时间段内的回流客人数及金额
//        Map<String,Object> BackFlowCustomer=this.statisticDao.queryBackFlowCustomer(sTime,BackFlowTime,eTime,Customers);
//        return BackFlowCustomer;
//    }
////    //重置时间节点
////    public int test()
////    {
////        //查询
////        List<OrderInfo> orderInfoList= this.orderServicer.queryAllOrderList();
////        for (OrderInfo o:orderInfoList
////             ) {
////
////        }
////
////    }


}


/*
package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.dao.StatisticDao;
import com.wsd.smartcarwasher.dao.WashServiceDao;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.util.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StatisticService {
    private static final Logger logger = LoggerFactory.getLogger(StatisticService.class);

    @Resource
    private StatisticDao statisticDao;

    @Resource
    private MachineService machineService;

    @Resource
    private WashServiceDao washServiceDao;

    public Map<String, Object> queryTurnoverTrend(String type, List<Integer> machineIds) {
        String dateFormat = getDateFormat(type);
        List<OrderStatistics> statistics = statisticDao.queryTurnoverTrendOfMachines(dateFormat, machineIds);
        return changeStatisticToMap(statistics);
    }

    private Map<String, Object> changeStatisticToMap(List<OrderStatistics> statistics) {
        List<String> times = statistics.stream().map(OrderStatistics::getTime).collect(Collectors.toList());
        List<BigDecimal> turnovers = statistics.stream().map(OrderStatistics::getTurnover).collect(Collectors.toList());
        List<Integer> orderSizes = statistics.stream().map(OrderStatistics::getOrderSize).collect(Collectors.toList());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("xLabels", times);
        resultMap.put("turnover_data", turnovers);
        resultMap.put("orders_data", orderSizes);
        return resultMap;
    }

    private String getDateFormat(String type) {
        String dateFormat;
        switch (type) {
            case "week":
                dateFormat = "%Y-%u";
                break;
            case "month":
                dateFormat = "%Y-%m";
                break;
            case "day":
            default:
                dateFormat = "%Y-%m-%d";
        }
        return dateFormat;
    }

    public Pagination<OrderInfo> queryOrderInfoWithPagination(List<Integer> machineIds, int pageNum, int pageSize) {
        List<OrderInfo> orders = queryOrderInfoByMachineIds(machineIds);
        return new Pagination<>(pageNum, pageSize, orders);
    }

    public List<OrderInfo> queryUserOrder(String userId) {
        List<OrderInfo> orders = statisticDao.queryUserOrder(userId);
        if (orders == null) {
            orders = Collections.emptyList();
        }
        return orders;
    }

    */
/**
     * 查询用户未完成的订单
     * @param userId 用户id
     * @return 返回用户未完成的订单
     *//*

    public Map<String, List<OrderInfo>> queryUserUnfinishedOrders(String userId) {
        List<OrderInfo> orders = queryUserOrder(userId);
        List<OrderInfo> unPayedOrders = new ArrayList<>();
        List<OrderInfo> unConsumedOrders = new ArrayList<>();
        for (OrderInfo order: orders) {
            if (order.getPayStatus() != Global.ORDER_PAY_STATUS_PAID) {
                unPayedOrders.add(order);
            } else if (order.getConsumed() != Global.ORDER_IS_CONSUMED && order.getStartTime() == null) {
                unConsumedOrders.add(order);
            }
        }
        Map<String, List<OrderInfo>> orderMap = new HashMap<>();
        orderMap.put("unPayedOrders", unPayedOrders);
        orderMap.put("unConsumedOrders", unConsumedOrders);
        return orderMap;
    }

    public List<OrderPieStatistic> getStatisticInfo(List<Integer> machineIds, String type) {
        List<OrderInfo> orders = queryOrderInfoByMachineIds(machineIds);
        return statisticOrderByType(orders, type);
    }

    */
/**
     * 按照时段/服务类型/支付方式来统计订单数
     *
     * @param orders 订单信息
     * @param type   统计方式
     * @return
     *//*

    private List<OrderPieStatistic> statisticOrderByType(List<OrderInfo> orders, String type) {
        if (orders == null) {
            orders = new ArrayList<>();
        }
        Map<String, List<OrderInfo>> groupMap;
        List<OrderPieStatistic> result = new ArrayList<>();
        if (Global.STATISTIC_TYPE_TIME_QUANTUM.equalsIgnoreCase(type)) {
            groupMap = groupByTimeQuantum(orders);
            result.add(new OrderPieStatistic("0时-6时", getStatisticInfoFromMap(groupMap, "0")));
            result.add(new OrderPieStatistic("6时-12时", getStatisticInfoFromMap(groupMap, "1")));
            result.add(new OrderPieStatistic("12时-18时", getStatisticInfoFromMap(groupMap, "2")));
            result.add(new OrderPieStatistic("18时-24时", getStatisticInfoFromMap(groupMap, "3")));
        } else if (Global.STATISTIC_TYPE_SERVICE_TYPE.equalsIgnoreCase(type)) {
            groupMap = groupByServiceType(orders);
            List<WashService> services = washServiceDao.queryAllWashServices();
            for (WashService washService : services) {
                result.add(new OrderPieStatistic(washService.getName(), getStatisticInfoFromMap(groupMap, String.valueOf(washService.getId()))));
            }
        } else if (Global.STATISTIC_TYPE_PAY_WAY.equalsIgnoreCase(type)) {
            groupMap = groupByPayWay(orders);
            result.add(new OrderPieStatistic("会员卡", getStatisticInfoFromMap(groupMap, "2")));
            result.add(new OrderPieStatistic("微信支付", getStatisticInfoFromMap(groupMap, "1")));
        }
        return result;
    }

    private Map<String, List<OrderInfo>> groupByTimeQuantum(List<OrderInfo> orders) {
        return orders.parallelStream()
                .collect(Collectors.groupingBy(order -> order.getCreateTime() == null ? null : String.valueOf(order.getCreateTime().getHours() / 6)));
    }

    private Map<String, List<OrderInfo>> groupByServiceType(List<OrderInfo> orders) {
        return orders.parallelStream().collect(Collectors.groupingBy(order -> String.valueOf(order.getServiceId())));
    }

    private Map<String, List<OrderInfo>> groupByPayWay(List<OrderInfo> orders) {
        return orders.parallelStream().collect(Collectors.groupingBy(order -> String.valueOf(order.getPayWayCode())));
    }

    private Integer getStatisticInfoFromMap(Map<String, List<OrderInfo>> group, String key) {
        List<OrderInfo> value = group.get(key);
        if (CollectionUtils.isEmpty(value)) {
            return 0;
        }
        return value.size();
    }

    private List<OrderInfo> queryOrderInfoByMachineIds(List<Integer> machineIds) {
        List<OrderInfo> orders = statisticDao.queryOrderInfoByMachineIds(machineIds);
        if (orders == null) {
            return Collections.emptyList();
        }
        return orders;
    }

    public Map<String, Object> getStatistics(Partner partner) {
        List<Machine> machines = machineService.getMachinesByPartnerId(partner.getId());
        if (CollectionUtils.isEmpty(machines)) {
            return null;
        }
        List<Integer> machineIds = machines.parallelStream().map(Machine::getId).distinct().collect(Collectors.toList());
        List<OrderInfo> orders = queryOrderInfoByMachineIds(machineIds);
        return getTurnoverStatistics(orders, true);
    }

    */
/**
     * 统计营业额信息
     *
     * @param orders   所有订单信息
     * @param isRunner 是否是运营段显示
     * @return 营业额信息
     *//*

    private Map<String, Object> getTurnoverStatistics(List<OrderInfo> orders, boolean isRunner) {
        if (orders == null) {
            orders = new ArrayList<>();
        }
        Date date = DateUtil.getSysDate();
        Date dateBack7 = DateUtil.getDateBack("6");
        Date dateBack30 = DateUtil.getDateBack("29");
        BigDecimal turnover_1 = new BigDecimal(0.00f);
        BigDecimal turnover_7 = new BigDecimal(0.00f);
        BigDecimal turnover_30 = new BigDecimal(0.00f);
        int orders_1 = 0;
        BigDecimal profit_1 = new BigDecimal(0.00f);
        for (OrderInfo order : orders) {
            if (order.getCreateTime().getTime() > date.getTime()) {
                orders_1 = orders_1 + 1;
                turnover_1 = turnover_1.add(order.getOrderPrice());
                profit_1 = profit_1.add(order.getOrderPrice().multiply(order.getProfitRatio()));
            }
            if (order.getCreateTime().getTime() > dateBack7.getTime()) {
                turnover_7 = turnover_7.add(order.getOrderPrice());
            }
            if (order.getCreateTime().getTime() > dateBack30.getTime()) {
                turnover_30 = turnover_30.add(order.getOrderPrice());
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("turnover_1", turnover_1.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        result.put("turnover_7", turnover_7.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        result.put("turnover_30", turnover_30.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        if (isRunner) {
            result.put("profit_1", profit_1.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }
        result.put("orders_1", orders_1);
        return result;
    }

    */
/**
     * pc端查询营业额统计信息
     *
     * @param machineId 机器id
     * @return 营业额统计信息
     *//*

    public Map<String, Object> getPcTurnoverStatistics(String machineId) {
        List<OrderInfo> orders = statisticDao.queryOrderInfoByMachineId(machineId);
        return getTurnoverStatistics(orders, false);
    }

    */
/**
     * pc端查询营业额和订单数趋势
     *
     * @param type      按照月/周/日来查询
     * @param machineId 机器id，为空则不区分机器
     * @return 营业额和订单数趋势
     *//*

    public Map<String, Object> queryPcTurnoverTrend(String machineId, String type) {
        String dateFormat = getDateFormat(type);
        List<OrderStatistics> statistics = statisticDao.queryTurnoverTrend(dateFormat, machineId);
        return changeStatisticToMap(statistics);
    }

    */
/**
     * pc端查询机器饼图统计信息
     *
     * @param machineId 机器id，为空则不区分机器
     * @param type      统计方式
     * @return 饼图统计信息
     *//*

    public List<OrderPieStatistic> getPcPieChart(String machineId, String type) {
        List<OrderInfo> orders = statisticDao.queryOrderInfoByMachineId(machineId);
        return statisticOrderByType(orders, type);
    }

    public OrderInfo queryOrderInfoByOrderSn(String orderSn) {
        return statisticDao.queryOrderInfoByOrderSn(orderSn);
    }
}
*/
